import {BaseService} from 'egg-cool-service';

/**
 * 商品-点赞
 */
export default class GoodsLikeService extends BaseService {

    /**
     * 点赞
     * @param param
     */
    async add (param) {
        const {id} = param;
        const {openid} = this.ctx.wx_decoded;
        let product = await this.getRepo ().goods.Like.findOne ({productId : id , openid});
        try {
            if ( !product ) {
                await this.getRepo ().goods.Like.save ({productId : id , openid});
                return id;
            } else {
                // throw new Error('已经点赞！不可重复操作')
                // await this.getRepo().goods.Like.update({productId:id,openid});
                return id;
            }
        } catch (e) {
            throw new Error ('收藏功能崩溃~');
        }

    }

    /**
     * 取消点赞
     * @param param
     */
    async cancel (param) {
        const {id} = param;
        const {openid} = this.ctx.wx_decoded;
        let product = await this.getRepo ().goods.Like.findOne ({productId : id , openid});
        if ( !product ) {
            throw new Error ('查询不到此条数据');
        } else {
            await this.getRepo ().goods.Like.delete ({productId : id , openid});
            return id;
        }
    }

    async list () {
        const {openid} = this.ctx.wx_decoded;
        const sql = `
        SELECT
            a.id,a.productId,
            d.name AS productName,d.bannerImage AS bannerImage,d.files AS files
        FROM
            goods_like a
            LEFT JOIN goods_product d on a.productId = d.id
        WHERE 1 = 1
            ${ this.setSql (openid , 'and a.openid = ?' , [openid]) }
        GROUP BY a.id
        `;
        const result = await this.nativeQuery (sql);
        result.forEach (item => {
            item.bannerImage = item.bannerImage ? JSON.parse (item.bannerImage) : {};
            if ( item.bannerImage.url ) {
                item.bannerImage.url = item.bannerImage.url + this.app.config.pictureSplit.logo;
            }
            let files = item.files ? JSON.parse (item.files) : [];
            // item.files = files.map(data=>{
            //     data.url = data.url + this.app.config.pictureSplit.qianyouzhuo
            //     return data
            // })
            item.imgCount = files.length;
        });
        return result;
    }

}
